package com.yanqu.road.server.gameplayer.module.player;

import com.yanqu.road.entity.config.skin.SkinInfo;
import com.yanqu.road.entity.estatewar.palace.PalaceFloorConfig;
import com.yanqu.road.entity.estatewar.palace.UserPalaceData;
import com.yanqu.road.entity.log.LogEstateWarDailyReward;
import com.yanqu.road.logic.bussiness.player.UserEstateWarBussiness;
import com.yanqu.road.server.gameplayer.module.skin.SkinModule;
import com.yanqu.road.server.manger.ConfigMgr;
import com.yanqu.road.server.manger.config.SkinMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.palace.PalaceActivity;
import com.yanqu.road.server.manger.palace.PalaceActivityMgr;
import com.yanqu.road.server.pb.EstateWarPb;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.enums.eRedHotNotifyType;
import com.yanqu.road.entity.estatewar.EstateFloorInfo;
import com.yanqu.road.entity.estatewar.EstateWarRecord;
import com.yanqu.road.entity.estatewar.UserEstateWarData;
import com.yanqu.road.pb.estatewar.EstateWarProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.cmd.estatewar.task.UserInfoChangeTask;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.config.EstateWarConfigMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.EstateWarMgr;
import com.yanqu.road.server.pb.WorldMessagePb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class EstateWarModule extends GeneralModule {

    private UserEstateWarData userEstateWarData;

    private LinkedList<EstateWarRecord> recordList;

    private Object lockObj = new Object();

    public EstateWarModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean afterLoadData() {
        initEstateWarData();
        return true;
    }

    @Override
    public boolean saveData() {
        if(null != userEstateWarData) {
            if (userEstateWarData.isInsertOption()) {
                UserEstateWarBussiness.addUserEstateWarData(userEstateWarData);
            } else if (userEstateWarData.isUpdateOption()) {
                UserEstateWarBussiness.updateUserEstateWarData(userEstateWarData);
            }
        }
        List<EstateWarRecord> tempRecordList = getRecordList();
        for (EstateWarRecord record : tempRecordList) {
            if (record.isInsertOption()) {
                UserEstateWarBussiness.addEstateWarRecord(record);
            }else if(record.isUpdateOption()) {
                UserEstateWarBussiness.updateEstateWarRecord(record);
            }
        }
        return true;
    }

    @Override
    public boolean loadData() {
        recordList = UserEstateWarBussiness.getEstateWarRecordList(player.getUserId(), GameConfig.ESTATE_WAR_MAX_RECORD_NUM);
        userEstateWarData = UserEstateWarBussiness.getUserEstateWarData(player.getUserId());
        EstateWarMgr.setUserEstateWarData(userEstateWarData);
        return true;
    }

    @Override
    public void loginSendMsg() {
        syncUserEstateWarData();
        checkDailyReward();
    }

    public void initSystem(){
        log.info("user:{} unlock estate system", player.getUserId());
        initEstateWarData();
        syncUserEstateWarData();
    }

    private void initEstateWarData(){
        initUserEstateWarData();
        checkEstateSkin();
        EstateWarMgr.setUserEstateWarData(userEstateWarData);
    }

    public void resetOneDay(){
        if(null != userEstateWarData) {
            long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
            if (userEstateWarData.getModifyTime() < zeroTime) {
                userEstateWarData.setWorshipValue(0);
                userEstateWarData.setModifyTime(zeroTime);
                syncUserEstateWarData();
            }
        }
    }

    public void syncUserEstateWarData(){
        EstateWarProto.EstateWarUserDataMsg.Builder msg = EstateWarPb.parseEstateWarUserDataMsg(userEstateWarData);
        if(null != msg) {
            player.sendPacket(Protocol.U_ESTATE_WAR_USER_DATA, EstateWarPb.parseEstateWarUserDataMsg(userEstateWarData));
        }
    }

    private void checkRedHotNotify(){
        if(null == userEstateWarData){
            return;
        }
        long lastNotifyTime = userEstateWarData.getLastBeAttackNotifyTime();
        int count = 0;
        for(EstateWarRecord estateWarRecord : recordList){
            if(estateWarRecord.getRecordTime() > userEstateWarData.getLastBeAttackNotifyTime()){
                count++;
                if(estateWarRecord.getRecordTime() > lastNotifyTime){
                    lastNotifyTime = estateWarRecord.getRecordTime();
                }
            }
        }
        if(count > 0){
            userEstateWarData.setLastBeAttackNotifyTime(lastNotifyTime);
            WorldMessageProto.RedHotNotifyMsg.Builder redHotMsg = WorldMessagePb.parseRedHotNotifyMsg(eRedHotNotifyType.EstateWarBeAttack.getValue(), count, "");
            player.sendPacket(Protocol.U_RED_HOT_NOTIFY, redHotMsg);
        }
    }

    public void checkDailyReward(){
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        if(null == userEstateWarData){
            return;
        }
        synchronized (lockObj) {
            if (userEstateWarData.getGetDailyRewardTime() >= zeroTime) {//已经领取奖励
                return;
            }

            EstateFloorInfo floorInfo = EstateWarConfigMgr.getEstateFloorInfo(userEstateWarData.getType(), userEstateWarData.getPos());
            if (null != floorInfo) {
                String mailTitle = MultipleLanguageMgr.getContent(MailManager.ESTATE_WAR_DAILY_REWARD_TITLE, player.getLanguage());
                String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.ESTATE_WAR_DAILY_REWARD_CONTENT, player.getLanguage()),
                        EstateWarConfigMgr.getEstateFloorName(userEstateWarData.getType(), userEstateWarData.getPos(), player.getLanguage()));
                String reward = PropertyHelper.parsePropertyToString(floorInfo.getDailyReward());
                MailManager.sendMail(player.getUserId(), eMailType.DAILY.getValue(), reward, mailContent, mailTitle);
                AutoLogMgr.add(new LogEstateWarDailyReward(getUserId(),reward));
//                LogMgr.addLogEstateWarDailyReward(player.getUserId(), reward);
            }
            //设置领取时间
            userEstateWarData.setGetDailyRewardTime(zeroTime);
        }
    }

    public void addRecord(EstateWarRecord record) {
        synchronized (recordList) {
            if (recordList.size() >= GameConfig.ESTATE_WAR_MAX_RECORD_NUM) {
                recordList.removeLast();
            }
            recordList.addFirst(record);
        }
    }

    public List<EstateWarRecord> getRecordList() {
        List<EstateWarRecord> tempRecordList;
        synchronized (recordList) {
            tempRecordList = new ArrayList<>(recordList);
        }
        return tempRecordList;
    }

    /**
     * 府邸赚速加成
     */
    public int getEarnSpeedAddition(){
        if(null != userEstateWarData){
            EstateFloorInfo floorInfo = EstateWarConfigMgr.getEstateFloorInfo(userEstateWarData.getType(), userEstateWarData.getPos());
            if(null != floorInfo){
                return floorInfo.getEarnSpeedAddition();
            }
        }
        return 0;
    }

    public UserEstateWarData getUserEstateWarData() {
        return userEstateWarData;
    }

    //是否可以开启家具目标
    public boolean isCanOpenFurnitureTargetTask() {
        if (userEstateWarData == null) {
            return false;
        }
        return userEstateWarData.getMaxType() >= GameConfig.WINGROOM_TARGE_OPEN_COND;
    }

    public void onEstateFloorChange(){
        player.getModule(EarnSpeedModule.class).scheduleAddSilver();
    }

    public void userInfoChange(boolean isUpdateAbility){
        if(null != userEstateWarData){
            if(userEstateWarData.getType() > 0 && userEstateWarData.getPos() > 0){
                EstateWarMgr.addTask(new UserInfoChangeTask(player, userEstateWarData.getType(), userEstateWarData.getPos(), isUpdateAbility));
            }
        }
    }

    private void initUserEstateWarData(){
        if(null == userEstateWarData) {
            long nowTime = System.currentTimeMillis() / 1000;
            UserEstateWarData estateWarData = new UserEstateWarData();
            estateWarData.setUserId(player.getUserId());
            estateWarData.setType(1);
            estateWarData.setPos(1);
            estateWarData.setCrossType(0);
            estateWarData.setCrossPos(0);
            estateWarData.setWorshipValue(0);
            estateWarData.setMaxType(0);
            estateWarData.setMaxPos(0);
            estateWarData.setModifyTime(nowTime);
            estateWarData.setGetDailyRewardTime(nowTime);
            estateWarData.setInsertOption();
            userEstateWarData = estateWarData;
        }
    }

    /**
    * 描述：变更府邸皮肤
    * 作者：zrq
    * 时间：2022/1/21
    * 参数：
    皮肤编号
    * 返回值：是否成功
    **/
    public int changeSkin(int skinId){
        if(null == userEstateWarData){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        if(!SkinMgr.isEstateSkin(skinId)){
            return GameErrorCode.E_ESTATE_WAR_NO_ESTATE_SKIN;
        }
        SkinInfo skinInfo = SkinMgr.getSkinInfo(skinId);
        int belongRole = skinInfo.getBelongRole();

        if(belongRole < 100 && !EstateWarConfigMgr.canChangEstateSkinType(skinInfo.getBelongRole())){
            // 小于100的才需要哦安短
            return GameErrorCode.E_ESTATE_WAR_NO_CHANGE_ESTATE_SKIN_TYPE;
        }
        if(skinInfo.getBelongRole() < 7){
            if(skinInfo.getBelongRole() > userEstateWarData.getType()){
                return GameErrorCode.E_ESTATE_WAR_NO_CHANGE_ESTATE_SKIN_TYPE;
            }
        }else if (belongRole == 7){
            PalaceActivity palaceActivity = PalaceActivityMgr.getInTimePalaceActivity();
            if(null == palaceActivity){
                return GameErrorCode.E_PALACE_ACTIVITY_NO_FOUND;
            }
            UserPalaceData userPalaceData = palaceActivity.getUserPalaceData(player.getUserId());
            if(null == userPalaceData){
                return GameErrorCode.E_ESTATE_WAR_NO_CHANGE_ESTATE_SKIN_TYPE;
            }
            PalaceFloorConfig palaceFloorConfig = palaceActivity.getPalaceFloorConfig(userPalaceData.getPos());
            if(palaceFloorConfig.getSkinsReward() != skinId){
                return GameErrorCode.E_ESTATE_WAR_NO_CHANGE_ESTATE_SKIN_TYPE;
            }
        }else {
            boolean skinExist = player.getModule(SkinModule.class).isSkinExist(skinId);
            if (!skinExist) {
                return GameErrorCode.E_ESTATE_WAR_NO_ESTATE_SKIN;
            }
        }
        userEstateWarData.setEstateSkinId(skinId);
        syncUserEstateWarData();
        return 0;
    }

    /**
    * 描述：检测府邸皮肤
    * 作者：zrq
    * 时间：2022/1/25
    * 参数：

    * 返回值：
    **/
    private void checkEstateSkin(){
        if(null != userEstateWarData){
            int maxType = userEstateWarData.getMaxType();
            if(userEstateWarData.getType() > maxType){
                maxType = userEstateWarData.getType();
            }
            for(int tempType = maxType; tempType > 0; tempType--){
                int estateSkinId = ConfigMgr.getEstateSkinId(tempType);
                unlockEstateSkin(estateSkinId);
            }
            int estateSkinId = ConfigMgr.getEstateSkinId(userEstateWarData.getType());
            if(userEstateWarData.getEstateSkinId() == 0){
                userEstateWarData.setEstateSkinId(estateSkinId);
            }else {
                if(estateSkinId != userEstateWarData.getEstateSkinId()){
                    SkinInfo skinInfo = SkinMgr.getSkinInfo(estateSkinId);
                    SkinInfo curSkinInfo = SkinMgr.getSkinInfo(userEstateWarData.getEstateSkinId());
                    if(null != skinInfo && null != curSkinInfo){
                        if(curSkinInfo.getBelongRole() < 7) {
                            if (curSkinInfo.getBelongRole() > userEstateWarData.getType()) {//当前皮肤等级大于限制
                                userEstateWarData.setEstateSkinId(estateSkinId);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
    * 描述：解锁府邸皮肤
    * 作者：zrq
    * 时间：2022/1/25
    * 参数：
    府邸皮肤编号
    * 返回值：
    **/
    public void unlockEstateSkin(int estateSkinId){
        if(estateSkinId > 0){
            SkinModule skinModule = player.getModule(SkinModule.class);
            if(!skinModule.isSkinExist(estateSkinId)){//不存在才解锁
                skinModule.useSkin(estateSkinId);
            }
        }
    }
}
